//
//  MEPrototypeCollection.m
//  MapEditor
//
//  Created by Eric on 3/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MEPrototypeTabView.h"
#import "RegexKitLite.h"
#import "MEPrototype.h"
#import "MEController.h"
#import "MEDefine.h"

@implementation MEPrototypeTabView

- (void) awakeFromNib
{
    [super awakeFromNib];
	[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
}


- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{    
	NSPasteboard *pboard = [sender draggingPasteboard];
	if ([[pboard types] containsObject:NSFilenamesPboardType])
	{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *filePaths = [pboard propertyListForType:NSFilenamesPboardType];
        for(NSString* filePath in filePaths)
        {
            
            BOOL isDirectory;
            BOOL fileExst = [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
            
            if (fileExst) {
                if (isDirectory) {
                    return NSDragOperationCopy;
                }else{
                    BOOL hasItem = [self.tabViewItems count]>0;
                    if (hasItem) {
                        NSString* regex = @"[.](jpg|jpeg|bmp|png)$";
                        NSString* lowcase = [filePath lowercaseString];
                        return [lowcase isMatchedByRegex:regex];
                    }
                }
                return NSDragOperationNone;
            }
        }
	}
	
	return NSDragOperationNone;
}

- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
{
	return NSDragOperationEvery;
}

- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
{
	return [self draggingEntered:sender];
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
	NSPasteboard *pboard = [sender draggingPasteboard];
	if ([[pboard types] containsObject:NSFilenamesPboardType])
	{
		NSArray *filePaths = [pboard propertyListForType:NSFilenamesPboardType];
        for(NSString* filePath in filePaths)
        {
            NSLog(@"fileName=%@", filePath);
            
            BOOL isDirectory;
            BOOL fileExst = [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
            if (!fileExst) {
                continue;
            }
            if (isDirectory) {
                NSArray *fileListTmp = [fileManager contentsOfDirectoryAtPath:filePath error:nil];
                NSMutableArray* prototypeList = [NSMutableArray arrayWithCapacity:[fileListTmp count]];
                NSString* regex = @"[.](jpg|jpeg|bmp|png)$";
                for(NSString* fileName in fileListTmp){
                    NSString* lowcase = [fileName lowercaseString];
                    if ([lowcase isMatchedByRegex:regex]) {
                        NSString* subPath = [NSString stringWithFormat:@"%@/%@", filePath, fileName];
                        NSImage *image = [[[NSImage alloc]initWithContentsOfFile:subPath] autorelease];                    
                        MEPrototype *prototype = [[MEPrototypeMgr instance] createPrototype];
                        prototype.filePath = subPath;
                        prototype.image = image;
                        prototype.name = [fileName stringByDeletingPathExtension];
                        [prototypeList addObject:prototype];
                    }
                }
                [prototypeList sortUsingComparator:(NSComparator)^(MEPrototype *m1, MEPrototype *m2){
                    return [m1.name compare:m2.name]; 
                }];
                NSViewController *itemCtrl = [[NSViewController alloc] init];
                [NSBundle loadNibNamed:@"MEPrototypeCollection" owner: itemCtrl];            
                [((MEPrototypeTabItemView*)itemCtrl.view).collection setContent:prototypeList];
                
                NSString* fileName = [filePath lastPathComponent];
                NSTabViewItem* item = [[NSTabViewItem alloc] init]; 
                //NSNumber *myNum = [[NSNumber alloc] initWithInt:3];
                //NSTabViewItem *item = [[NSTabViewItem alloc] initWithIdentifier:myNum];
                item.label = fileName;
                item.view = itemCtrl.view;            
                [self addTabViewItem:item];
                [self selectTabViewItem:item];
                [[MEController instance].prototypeTabPopBtn addItemWithTitle:fileName];
                [[MEController instance].prototypeTabPopBtn selectItemAtIndex:[self indexOfTabViewItem:item]];
            }else{
                MEPrototype *prototype = [[MEPrototypeMgr instance] createPrototype];
                prototype.filePath = filePath;
                prototype.image = [[[NSImage alloc]initWithContentsOfFile:filePath] autorelease];
                prototype.name = [[filePath lastPathComponent] stringByDeletingPathExtension];
                
                NSCollectionView* collection = [self.selectedTabViewItem.view collection];
                NSArray* content = collection.content;
                NSMutableArray* newContent = [NSMutableArray arrayWithArray:content];
                [newContent addObject:prototype];
                [newContent sortUsingComparator:(NSComparator)^(MEPrototype *m1, MEPrototype *m2){
                    return [m1.name compare:m2.name];
                    
                }];
                [collection setContent:newContent];    
                [collection setSelectionIndexes:[NSIndexSet indexSetWithIndex:[newContent indexOfObject:prototype]]];
            }
            
            //[delegate performSelector:@selector(acceptFilenameDrag)  withObject:[filenames objectAtIndex:i]];
        }
        [pboard clearContents];
        return YES;
    }
    return NO;
}
@end


@implementation MEPrototypeTabItemView
@synthesize collection;
@end


@implementation MEPrototypeCollectionItemView
-(IBAction)prototypeNameChanged:(id)sender
{
    NSTextField* textField = sender;
    [textField setEditable:NO];
    MEPrototype* prototype = [[MEController instance] selectedPrototype];
    prototype.name = [sender stringValue];
    [[self window] makeFirstResponder:self];
}
- (void)rightMouseDown:(NSEvent *)event{  
    if (selected) {
        NSMenu* rightClick =  [ [NSMenu alloc] initWithTitle:@"RightClick"];
        MEPrototype* prototype = [[MEController instance] selectedPrototype];
        //Add NSMenuItem(s) to the rightClick NSMenu
        NSMenuItem* duplicate = [[[NSMenuItem  alloc] init] autorelease];
        [duplicate setTitle:@"Duplicate"];
        [duplicate setRepresentedObject:prototype];
        [duplicate setAction:@selector(duplicatePrototype:)];
        [duplicate setTarget:self];
        [rightClick addItem:duplicate];
        NSMenuItem* remove = [[[NSMenuItem  alloc] init] autorelease];
        [remove setTitle:@"Remove"];
        [remove setRepresentedObject:prototype];
        [remove setAction:@selector(removePrototype:)];
        [remove setTarget:self];
        [rightClick addItem:remove];

        
        [NSMenu popUpContextMenu:rightClick withEvent:event forView:self];
    }
}

-(void)removePrototype:(NSMenuItem*)item{
    NSCollectionView* collection = [[MEController instance].prototypeTabView.selectedTabViewItem.view collection];
    NSMutableArray* content = [NSMutableArray arrayWithArray:collection.content];
    [content removeObject:item.representedObject];
    [collection setContent:content];
    [[MEPrototypeMgr instance] removePrototype:item.representedObject];
}
-(void)duplicatePrototype:(NSMenuItem*)item{
    MEPrototype* prototype = item.representedObject;
    MEPrototype* copy = [[MEPrototypeMgr instance] duplicate:item.representedObject];
    NSCollectionView* collection = [[MEController instance].prototypeTabView.selectedTabViewItem.view collection];
    NSMutableArray* content = [NSMutableArray arrayWithArray:collection.content];
    [content insertObject:copy atIndex:[content indexOfObject:prototype]+1];
    [collection setContent:content];
    [collection setNeedsDisplay:YES];
}


- (void)mouseDown:(NSEvent *)theEvent{
    if (!selected) {
        [super mouseDown:theEvent];        
        MEController* ctrl = [MEController instance];
        [ctrl refreshPrototypeInfo];
    }    
}
@end


@implementation MEPrototypeLabel
- (void)rightMouseDown:(NSEvent *)event{   
    [self.superview rightMouseDown:event];
}
@end


@implementation MEProrotypeImageView
- (void)rightMouseDown:(NSEvent *)event{   
    [self.superview rightMouseDown:event];
}
- (void)mouseDown:(NSEvent *)theEvent{
    MEPrototypeCollectionItemView* itemView = (MEPrototypeCollectionItemView*)self.superview;
    if (itemView.selected) {
        MEPrototype* prototype = [[MEController instance] selectedPrototype];
        if (prototype) {
            NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSDragPboard];
            [pb clearContents];
            //[pb setPropertyList:[NSArray arrayWithObject:[NSNumber numberWithInteger:prototype.sid]] forType:NSStringPboardType];
            [pb setString:[NSString stringWithFormat:@"%d", prototype.sid] forType:NSStringPboardType];
            //[pb setPropertyList:[NSString stringWithFormat:@"%d", prototype.sid] forType:NSStringPboardType];
            
            
            
            NSPoint pos = [theEvent locationInWindow];
            pos = [self convertPoint:pos fromView:nil];
            
            NSSize size = [prototype.image size];
            pos.x -= size.width / 2;
            pos.y -= size.height / 2;
            
            [self dragImage:prototype.image at:pos offset:NSZeroSize event:theEvent pasteboard:pb source:self slideBack:YES];
        }
    }else{
        [itemView mouseDown:theEvent];
    }
}

@end


@implementation MEPrototypeTabDelegate

- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
    MEController* ctrl = [MEController instance];
    [ctrl refreshPrototypeInfo];
}

- (BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
    
    
    return YES;
}

- (void)tabView:(NSTabView *)tabView willSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
}

- (void)tabViewDidChangeNumberOfTabViewItems:(NSTabView *)tabView
{
    
}

@end
